package com.vitaf.cash.app.ui.fragment

import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import com.vitaf.cash.app.R
import com.vitaf.cash.app.common.VitafComFmtV2
import com.vitaf.cash.app.configs.GombeCreditApiPath
import com.vitaf.cash.app.configs.GombeCreditApiUrl
import com.vitaf.cash.app.configs.GombeCreditApiUrl.addCommonParams
import com.vitaf.cash.app.databinding.VitafActApplyDetailsChildItemBinding
import com.vitaf.cash.app.databinding.VitafFmtRepayBinding
import com.vitaf.cash.app.event.VitafEventData
import com.vitaf.cash.app.event.VitafEventPointType
import com.vitaf.cash.app.event.room.VitafPointManager
import com.vitaf.cash.app.request.IHttpCallback
import com.vitaf.cash.app.ui.activity.VitafPayStatusAct
import com.vitaf.cash.app.utils.VitafDensityUtil
import com.vitaf.cash.app.utils.VitafTitleBarUtil
import com.vitaf.cash.app.utils.helper.VitafProcessHp
import com.vitaf.cash.app.utils.shared.VitafSharedHp
import com.vitaf.cash.app.utils.shared.VitafSharedKey
import com.vitaf.cash.lib.adapter.VitafOnSingleClickListener
import org.json.JSONObject
import java.math.BigDecimal

/**
 * GombeCredit
 * @Author wwdeng
 * @CreateTime: 2024/12/10 14:53
 * @Annotation：待还款
 */
class VitafRepayFmt : VitafComFmtV2() {
    private var _binding: VitafFmtRepayBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "gombe credit reapy binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )

    public override var pageName: String = "Repay_Page"

    override fun createVitafContentView(inflater: LayoutInflater): View {
        _binding = VitafFmtRepayBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initializeVitafViews() {
        _binding?.repayTitleBarLayout?.setPadding(0, VitafTitleBarUtil.getStatusBarHeight() + VitafDensityUtil.dp2px(10f), 0, 0)
        _binding?.repayPageRefreshLayout?.setColorSchemeResources(R.color.theme, R.color.purple_500)
    }

    override fun setupVitafEventListeners() {
        _binding?.imgCustomer?.setOnClickListener(object : VitafOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                onClickCustomer(pageName)
            }
        })
        _binding?.repayPageRefreshLayout?.setOnRefreshListener {
            publishEventData(VitafEventData(VitafEventData.TYPE.GOMBECREDIT_PROCESS_REFRESH))
        }
        _binding?.btnRepay?.setOnClickListener(object : VitafOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_CLICK.LOAN_REPAY,"Repay Page")
                // TODO: 还款按钮 需上报所有埋点
                VitafPointManager.getInstance().manualReport()

                onGombeCreditPayAction()
            }
        })
    }

    override fun loadVitafData() {
        addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_PAGE.LOAN_REPAY_START)
    }

    /**
     * 设置还款信息
     */
    private fun showGombeCreditRepayInfo(data: JSONObject){
        _binding?.let { binding ->
            binding.textTotalRepayment.text = BigDecimal(data.optString("repayAmount")).stripTrailingZeros().toPlainString()
            binding.textCurrency.text = data.optString("currency")
            binding.textRepayDate.text = data.optString("repayDate")

            //逾期天数
            val overdueDay = data.optInt("overdueDay",0)
            if (overdueDay > 0){//已逾期 - 逾期天数
                binding.textRepayDueDate.text = String.format(getString(R.string.gombe_credit_repay_days_overdue),"$overdueDay")
                binding.textRepayDueDate.getShapeDrawableBuilder()
                    .setSolidColor(getColor(R.color.gombe_credit_FFFE4E33))
                    .intoBackground()
                binding.imageLeftTopCorner.setImageResource(R.mipmap.gombe_credit_image_repay_days_overdue_corner)
                binding.imageRightBottomCorner.setImageResource(R.mipmap.gombe_credit_image_repay_days_overdue_corner)
            } else {//未逾期 - 剩余还款天数
                binding.textRepayDueDate?.text = String.format(getString(R.string.gombe_credit_repay_days_left), data.optString("remainDay"))
                binding.textRepayDueDate.getShapeDrawableBuilder()
                    .setSolidColor(getColor(R.color.gombe_credit_FFFF9326))
                    .intoBackground()
                binding.imageLeftTopCorner.setImageResource(R.mipmap.gombe_credit_image_repay_days_left_corner)
                binding.imageRightBottomCorner.setImageResource(R.mipmap.gombe_credit_image_repay_days_left_corner)
            }

            binding.repayItemListLayout.removeAllViews()
            val detailItemList = data.optJSONArray("detailItemList")
            detailItemList?.let { itemList ->
                for (i in 0..< itemList.length()){
                    val childItem = itemList.optJSONObject(i)
                    val childView = VitafActApplyDetailsChildItemBinding.inflate(layoutInflater)
                    childView.textDetailsTitle.text = childItem.optString("showName")
                    childView.textDetailsTitle.setTextColor(getColor(R.color.gombe_credit_ffa8a8a8))
                    childView.textDetailsValue.text = childItem.optString("showDetail")
                    childView.textDetailsValue.setTextColor(getColor(R.color.gombe_credit_ff1d1e20))

                    childView.textOldValue.visibility = View.GONE
                    if (childItem.has("oldDetail")){
                        childView.textOldValue.visibility = View.VISIBLE
                        childView.textOldValue.text = childItem.optString("oldDetail")
                    }
                    childView.discountLayout.visibility = View.GONE
                    if (childItem.has("discount")){
                        childView.discountLayout.visibility = View.VISIBLE
                        childView.textDiscount.text = childItem.optString("discount")
                    }

                    childView.viewLine.visibility = View.VISIBLE
                    if (i == itemList.length() - 1){
                        childView.viewLine.visibility = View.GONE
                    }

                    binding.repayItemListLayout.addView(childView.root)
                }
            }
        }
    }

    /**
     * 链接还款
     */
    private fun showGombeCreditPayLink(linkUrl: String){
        val uri = Uri.parse(linkUrl)
        val intent = Intent(Intent.ACTION_VIEW, uri)
        startActivity(intent)
    }

    /**
     * pin还款
     */
    private fun showGombeCreditPayStatusAction(thirdOrderId: String){
        VitafPayStatusAct.start(requireContext(),thirdOrderId,binding.textRepayDate.text.toString())
    }

    /**
     * 获取还款信息
     */
    private fun loadGombeCreditRepayInfoAction(){
        val httpUrl = GombeCreditApiUrl.takeRequestUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_LOAN_REPAYMENT_INFO_PATH)
            put("oldFlag","YES")
        }
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                obj?.let {
                    showGombeCreditRepayInfo(it)
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideVitafLoading()
            }
        })
    }

    /**
     * 订单还款
     * 不减免 normal
     * 积分减免 score
     * 优惠券减免 coupon
     */
    private fun onGombeCreditPayAction(){
        showVitafLoading()
        val httpUrl = GombeCreditApiUrl.takeRequestUrl()
        val params = JSONObject().addCommonParams().apply {
            put("mobile", VitafSharedHp.takeGombeCreditSharedString(VitafSharedKey.GOMBECREDIT_MOBILE))
            put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_LOAN_REPAYMENT_MARKET_URL_PATH)
        }
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                hideVitafLoading()
                val obj = data.optJSONObject("obj")
                if (obj != null){
                    var linkUrl = obj.optString("url","")
                    if (linkUrl.isEmpty()){
                        linkUrl = obj.optString("repayUrl","")
                    }
                    //没有还款链接 - 需要进入还款状态页查询还款状态
                    if (linkUrl.isEmpty()){
                        val thirdOrderId = obj.optString("thirdOrderId")
                        if (thirdOrderId.isEmpty()){
                            showVitafToast("Transaction id is empty")
                            return
                        }
                        showGombeCreditPayStatusAction(thirdOrderId)
                    } else {
                        showGombeCreditPayLink(linkUrl)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                hideVitafLoading()
            }
        })
    }

    override fun onVitafPublishEvent(event: VitafEventData) {
        super.onVitafPublishEvent(event)
        when(event.eventType){
            VitafEventData.TYPE.GOMBECREDIT_PROCESS_REFRESHED,
            VitafEventData.TYPE.GOMBECREDIT_DATA_REFRESH -> {//收到刷新数据通知
                //待还款
                val isRepay = VitafProcessHp.isGombeCreditRepay()
                if (isRepay){
                    loadGombeCreditRepayInfoAction()
                }
            }
            else -> {
            }
        }
    }

    override fun hideVitafLoading() {
        super.hideVitafLoading()
        _binding?.repayPageRefreshLayout?.isRefreshing = false
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_PAGE.LOAN_REPAY_END)
        // TODO: 待还款关闭 需上报所有埋点
        VitafPointManager.getInstance().manualReport()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}